// profile.ts
Component({
  data: {
    userInfo: {
      avatarUrl: '/images/default-avatar.png',
      nickName: '美丽用户',
      phone: '138****8888'
    },
    cartCount: 0
  },

  methods: {
    checkLogin() {
      const isLoggedIn = wx.getStorageSync('isLoggedIn')
      const token = wx.getStorageSync('token')
      
      if (!isLoggedIn || !token) {
        wx.redirectTo({
          url: '/pages/login/login'
        })
        return false
      }
      return true
    },

    // 跳转到个人信息
    goToPersonalInfo() {
      wx.navigateTo({
        url: '/pages/personal-info/personal-info'
      })
    },

    // 退出登录
    logout() {
      wx.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            wx.removeStorageSync('isLoggedIn')
            wx.removeStorageSync('token')
            wx.removeStorageSync('userInfo')
            
            wx.reLaunch({
              url: '/pages/login/login'
            })
          }
        }
      })
    },

    handlerGobackClick() {
      wx.navigateBack({
        delta: 1
      })
    },

    // 跳转到预约记录
    goToMyOrders(e: any) {
      const status = e.currentTarget.dataset.status
      let url = '/pages/my-orders/my-orders'
      if (status) {
        url += `?status=${status}`
      }
      wx.navigateTo({ url })
    },

    // 跳转到购买记录
    goToMyProducts(e: any) {
      const type = e.currentTarget.dataset.type
      let url = '/pages/my-products/my-products'
      if (type) {
        url += `?type=${type}`
      }
      wx.navigateTo({ url })
    },

    // 跳转到购物车
    goToCart() {
      wx.navigateTo({
        url: '/pages/cart/cart'
      })
    },

    // 获取用户信息
    getUserInfo() {
      const userInfo = wx.getStorageSync('userInfo') || {
        avatarUrl: '/images/default-avatar.png',
        nickName: '游客',
        phone: '未绑定手机号'
      }
      this.setData({ userInfo })
    },

    // 更新购物车数量
    updateCartCount() {
      const cart = wx.getStorageSync('cart') || []
      const cartCount = cart.reduce((sum: number, item: any) => sum + item.quantity, 0)
      this.setData({ cartCount })
    }
  },

  lifetimes: {
    attached() {
      if (!this.checkLogin()) {
        return
      }
      this.getUserInfo()
      this.updateCartCount()
    }
  },

  // 监听页面显示
  pageLifetimes: {
    show() {
      this.updateCartCount()
    }
  }
})